<template>
	<view class="chat-detail-container">


		<!-- 顶部标题栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="back-arrow">←</text>
			</view>
			<text class="title">{{ chatTitle }}</text>
		</view>

		<!-- 聊天内容区域 -->
		<view class="chat-content" :class="'chat-'+(appParameters.length>0&&appParameters[0]['text-input']?'agent':'')"
			ref="chatContent">
			<view class="message-list" ref="messageList">
				<view class="message-item" v-for="(message,index) in messages" :key="message.id"
					:class="{ 'user-message': message.type === 'user', 'ai-message': message.type === 'ai' }">
					<view class="message-content">
						<view v-if="(message.imagePending||message.status==2||message.status==3)&&message.type === 'ai'&&outputType!='text'" class="image-placeholder">
							<view class="spinner"></view>
							<view class="spinner-text">正在生成中...<view>离开该页面不会中断任务生成</view>
							<view class="spinner-text-btn" v-if="message.status==2||message.status==3" @click="getVideoDetail('',message.messageId,index)">更新当前视频状态</view></view>
						</view>
						<div v-else-if="message.videoUrl" class="video-container">
							<video :src="message.videoUrl" class="message-video" :controls="true" autoplay></video>
							<view class="action-button download-btn copy-video" @click="copyContent(message.videoUrl)">
								<text>复制视频链接</text>
							</view>
						</div>
						<view v-else-if="message.htmlContent" class="content-container">
							<div class="html-content" v-html="message.htmlContent" @tap="handleHtmlImageTap"></div>
							<!-- 复制按钮 -->
							<block v-if="((message.type === 'ai'&&index>0) || message.type === 'user')&&!isTyping">
								<view class="action-button copy-btn"
									@click="copyContent(message.htmlContent)">
									<text>复制</text>
								</view>
							</block>

						</view>
						<view v-else-if="message.content" class="content-container">
							<text class="message-text">{{ message.content }}</text>
							<!-- 复制按钮 -->
							<block v-if="((message.type === 'ai'&&index>0) || message.type === 'user')&&!isTyping&&index>0">
								<view class="action-button copy-btn"
									@click="copyContent(message.htmlContent)">
									<text>复制</text>
								</view>
							</block>
						</view>
						<!-- 打字指示器 -->
						<text v-if="message.type === 'ai' && !message.htmlContent && message.status==2 && outputType=='text'"
							class="typing-indicator">正在输入...</text>
					</view>
					<view class="message-time">
						<text class="time-text">{{ message.time }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部输入区域 -->
		<view class="input-area">
			<!-- 图片上传区域（仅agent模式显示） -->
			<view v-if="outputType == 'image'&&appParameters.length > 0" class="upload-area">
				<view v-for="(item,id) in appParameters" :key="id">
					<view class="upload-container" @click="chooseImage" v-if="item['text-input']">
						<view v-if="!uploadedImage" class="upload-placeholder">
							<text class="upload-text">上传图片</text>
						</view>
						<image v-else :src="uploadedImage" class="uploaded-image" mode="aspectFit" />
						<view v-if="uploadedImage" class="remove-image" @click.stop="removeImage">
							<text class="remove-icon">×</text>
						</view>
					</view>

					<!-- 图片比例选择器 -->
					<view class="aspect-ratio-selector" v-if="item.select">
						<view class="ratio-buttons">
							<view v-for="(ratio,id) in item.select.options" :key="id"
								:class="['ratio-btn', { 'active': selectedRatio === ratio }]"
								@click="selectRatio(ratio)">
								<text class="ratio-text">{{ ratio }}</text>
							</view>
						</view>
					</view>

				</view>



			</view>

			<view class="input-wrapper">
				<view class="conversation-list-btn" @click="showConversationList">
					<text class="list-icon">≡</text>
				</view>
				<input class="message-input" v-model="inputMessage" placeholder="请输入消息..." :disabled="isTyping"
					@confirm="sendMessage" maxlength="3000" />
				<view class="send-btn" :class="isTyping ? 'disabled' : ''" @click="sendMessage">
					<text class="send-text">{{ isTyping ? '输入中...' : '发送' }}</text>
				</view>
			</view>
		</view>

		<!-- 会话列表弹窗 -->
		<view class="conversation-popup" v-if="showConversationPopup" @click.stop="hideConversationPopup">
			<view class="popup-content" :class="{ 'slide-out': isClosing }" @click.stop>
				<view class="popup-header">
					<text class="popup-title">会话列表</text>
					<view class="new-conversation-btn" @click="createNewConversation">
						<text class="new-conversation-text">+ 新建会话</text>
					</view>
				</view>

				<view class="popup-body">
					<view v-if="isLoading" class="loading-indicator">
						<text>加载中...</text>
					</view>

					<view v-else-if="conversationGroups.length === 0" class="empty-state">
						<text>暂无会话</text>
					</view>

					<view v-else>
						<block v-for="group in conversationGroups" :key="group.id">
						<view  class="conversation-group"
							@click="selectConversation(group)" v-if="group.conversationId">
							<text class="conversation-time">{{ group.updatedAt}}</text>
							<text class="group-title">{{ group.query }}</text>
						</view>
						</block>
					</view>
				</view>

				<view class="popup-footer">
					<view class="back-chat-btn" @click="hideConversationPopup">
						<text>返回对话</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 作文撰写弹窗 -->
		<view class="writing-popup" v-if="showWritingPopup&&appParameters.length > 0&&outputType=='text'">
			<view class="popup-content">

				<view class="form-group" v-for="(item, index) in appParameters" :key="index">
					<block v-if="item.select">
						<text class="form-label">{{item.select.label}}</text>
						<view class="type-buttons" v-if="item.select.options">
							<view v-for="type in item.select.options" :key="type"
								:class="['type-btn', { 'active': params[item.select.variable] === type }]"
								@click="params[item.select.variable] = type">
								<text>{{ type }}</text>
							</view>
						</view>
					</block>
					<block v-if="item['text-input']">
						<text class="form-label">{{item['text-input'].label}}</text>
						<input v-model="params[item['text-input'].variable]" class="word-count-input"
							:placeholder="item['text-input'].default" :maxlength="item['text-input'].max_length" />
					</block>
					<block v-if="item.number">
						<text class="form-label">{{item.number.label}}</text>
						<input type="number" :placeholder="item.number.default" v-model="params[item.number.variable]"
							class="word-count-input" maxlength="3000" />
					</block>
					<block v-if="item.paragraph">
						<text class="form-label">{{ item.paragraph.label }}</text>
						<textarea v-model="params[item.paragraph.variable]" class="topic-input"
							:placeholder="item.paragraph.default" :maxlength="item.paragraph.max_length"></textarea>
						<text v-if="item.paragraph.max_length"
							class="char-count">{{ params[item.paragraph.variable]?.length||0 }}/{{item.paragraph.max_length}}</text>
					</block>

				</view>

				<button class="generate-btn" @click="generateEssay">立即生成</button>
			</view>
		</view>

	</view>

	<!-- 图片预览弹窗 -->
	<view class="image-preview" v-if="showImagePreview" @tap="closeImagePreview">
		<image :src="previewImageUrl" class="preview-image" mode="aspectFit" @tap.stop />
		<view class="close-preview" @tap="closeImagePreview">
			<text class="close-icon">×</text>
		</view>
		<view class="save-tip">
			<text class="save-tip-text">长按图片可保存到相册</text>
		</view>
	</view>

</template>

<script>
	import {
		API_CONFIG
	} from '../../utils/config.js'
	import {
		uploadFile,
		get
	} from '../../utils/request.js'
	export default {
		data() {
			return {
				chatTitle: '对话详情',
				appId: '',
				showImagePreview: false,
				previewImageUrl: '',
				inputMessage: '',
				type: '',
				isTyping: false,
				uploadedImage: '',
				uploadedImageFile: null,
				streamBuffer: '', // 用于缓冲不完整的流式数据
				selectedRatio: '',
				outputType: '',
				conversationId: '',
				categoryId: '',
				messages: [{
					id: 1,
					type: 'ai',
					content: '你好！我是AI助手，有什么可以帮助你的吗？',
					time: this.getCurrentTime(),
					imageUrl: '',
					htmlContent: ''
				}],
				// 会话列表相关数据
				showConversationPopup: false,
				conversationGroups: [],
				isLoading: false,
				isClosing: false,
				// 作文撰写弹窗相关数据
				showWritingPopup: true,
				essayTopic: '',
				essayType: '',
				essayWordCount: '',
				params: {},
				// API参数配置
				appParameters: [],
				isLoadingParams: false
			}
		},

		onLoad(options) {
			if (options.id) {
				this.appId = options.id
			}
			if (options.title) {
				this.chatTitle = options.title
			}
			if (options.type) {
				this.type = options.type
			}
			if (options.categoryId) {
				this.categoryId = options.categoryId
			}
			if (options.outputType) {
				this.outputType = options.outputType
			}

			this.scrollToBottom()
		},

		// 页面显示时调用
		onShow() {
			if (this.appId) {
				this.fetchAppParameters()
			}
		},

		methods: {
			// 获取应用参数配置
			async fetchAppParameters() {
				try {
					this.isLoadingParams = true
					const response = await get('/api/dify/app/parameters', {
						appId: this.appId
					})
					
					// 保存参数配置
					if (response.data) {
						this.appParameters = response.data.user_input_form
						const id = this.appParameters.findIndex(obj=>obj.select)
						if(this.outputType=='image'&&id>-1){
							this.selectedRatio=this.appParameters[id]?.select?.options[0]
						}
						// 这里可以根据参数配置做一些初始化操作
					}
				} catch (error) {
					console.error('获取应用参数配置失败:', error)
					uni.showToast({
						title: '获取配置失败',
						icon: 'none'
					})
				} finally {
					this.isLoadingParams = false
				}
			},

			// 返回上一页
			goBack() {
				uni.switchTab({
					url:'/pages/index/index'
				})
			},

			// 显示会话列表弹窗
			showConversationList() {
				this.showConversationPopup = true
				this.loadConversationGroups()
			},

			// 隐藏会话列表弹窗 - 使用向左滑动画
			hideConversationPopup() {
				this.isClosing = true
				// 等待动画完成后再隐藏
				setTimeout(() => {
					this.showConversationPopup = false
					this.isClosing = false
				}, 300)
			},

			// 加载会话分组列表
			async loadConversationGroups() {
				try {
					this.isLoading = true
					const response = await fetch(API_CONFIG.BASE_URL + '/api/dify/conversation/group-list?appId=' +
						this.appId, {
							method: 'GET',
							headers: {
								'Authorization': `Bearer ${uni.getStorageSync('token')}`,
								'Content-Type': 'application/json'
							}
						})

					if (!response.ok) {
						throw new Error('请求失败: ' + response.status)
					}

					const data = await response.json()
					this.conversationGroups = data.data.list || []
					console.log(this.conversationGroups)
				} catch (error) {
					console.error('加载会话列表失败:', error)
					uni.showToast({
						title: '加载会话列表失败',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},

			// 选择会话
			async selectConversation(conversation) {
				try {
					this.hideConversationPopup()
					this.conversationId = conversation.conversationId
					// 调用会话详情接口
					const response = await fetch(API_CONFIG.BASE_URL + '/api/dify/conversation/detail-list?appId=' +
						this.appId + '&conversationId=' + conversation.conversationId, {
							method: 'get',
							headers: {
								'Authorization': `Bearer ${uni.getStorageSync('token')}`,
								'Content-Type': 'application/json'
							}
						})

					if (!response.ok) {
						throw new Error('请求失败: ' + response.status)
					}

					const data = await response.json()

					// 更新聊天标题
					// this.chatTitle = conversation.name || '对话详情'

					// 清空输入框
					this.inputMessage = ''
					this.selectedRatio = ''
					this.isTyping = false
					this.uploadedImage = ''

					// 这里可以根据接口返回的数据更新消息列表
					// 由于接口返回格式不确定，这里只是示例
					if (data.data && data.data.list) {
						let arr = []
						console.log('data.data.list====',data.data.list)
						data.data.list.map(msg => {
							arr.push({
								...msg,
								id: msg.id,
								type: 'user',
								content: '',
								time: this.formatTime(msg.createdAt),
								imageUrl: '',
								htmlContent: `<p>${msg.query}</p>${msg.params.inputs?.image_url?`<img src="${msg.params.inputs?.image_url}" width="100">`:''}`
							})
							if (msg.response) {
								// 过滤掉文字，只保留img标签内容
								let imgContent = msg.response || '';
								// 使用正则表达式提取所有img标签
								const imgRegex = /<img[^>]*>/g;
								const imgMatches = imgContent.match(imgRegex);
								const filteredContent = imgMatches ? imgMatches.join('') : '';
								const msgTips = msg.status==4?this.filterThinkTags(msg.response):''

								arr.push({
									...msg,
									id: msg.id,
									type: 'ai',
									content: '',
									status:msg.status,
									time: this.formatTime(msg.createdAt),
									imageUrl: '',
									videoUrl:msg.data?.video?.url,
									htmlContent: this.outputType == 'text' ? this.filterThinkTags(msg.response) :
										(this.outputType == 'image'?filteredContent:msgTips)
								})
							}
						})
						console.log(data, arr)
						this.messages = arr
					}

					// 滚动到底部
					this.scrollToBottom()
				} catch (error) {
					console.error('加载会话详情失败:', error)
					uni.showToast({
						title: '加载会话详情失败',
						icon: 'none'
					})
				}
			},

			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')
				return `${hours}:${minutes}`
			},

			// 新建会话
			createNewConversation() {
				this.hideConversationPopup()
				// 清空输入框
				this.inputMessage = ''
				this.conversationId = ''
				// 这里可以添加新建会话的逻辑
				this.isTyping = false
				this.messages = [{
					id: 1,
					type: 'ai',
					content: '你好！我是AI助手，有什么可以帮助你的吗？',
					time: this.getCurrentTime(),
					imageUrl: '',
					htmlContent: ''
				}]
			},

			// 生成作文
			generateEssay() {
				let isError = false
				let queryStr = ''
				this.appParameters.map(item => {
					if (item.select) {
						if (!this.params[item.select.variable] && item.select.required) {
							uni.showToast({
								title: item.select.label + '不能为空',
								icon: 'none'
							})
							isError = true
							return
						}
						queryStr+=item.select.label+'：'+this.params[item.select.variable]+'；'
					}
					if (item.number) {
						if (!this.params[item.number.variable] && item.number.required) {
							uni.showToast({
								title: item.number.label + '不能为空',
								icon: 'none'
							})
							isError = true
							return
						}
						queryStr+=item.number.label+'：'+this.params[item.number.variable]+'；'
					}
					if (item.paragraph) {
						if (!this.params[item.paragraph.variable] && item.paragraph.required) {
							uni.showToast({
								title: item.paragraph.label + '不能为空',
								icon: 'none'
							})
							isError = true
							return
						}
						queryStr+=item.paragraph.label+'：'+this.params[item.paragraph.variable]+'；'
					}


				})
				console.log(this.params)

				if (isError) {
					return
				}
				// 隐藏弹窗，展示输入框位置
				this.showWritingPopup = false

				// 设置输入框内容
				this.inputMessage = `按以下需求开始生成：<br/>`+queryStr

				// 可以选择自动发送消息
				this.sendMessage()
			},

			// 发送消息
			async sendMessage() {
				if (!this.inputMessage.trim() || this.isTyping) {
					return
				}
				const isMember = uni.getStorageSync('isMember')
				if (!isMember && this.type == 'agent') {
					uni.showModal({
						title: '非会员不能使用哦～',
						content: '快去升级成为会员吧',
						confirmText: '开通会员',
						success(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: `/pages/recharge/recharge`
								})
							}
						}
					})
					return
				}

				// 添加用户消息
				const userMessage = {
					id: Date.now(),
					type: 'user',
					htmlContent: this.uploadedImage?`<p>${this.inputMessage}</p><img src="${this.uploadedImage}" width="100">`:this.inputMessage,
					time: this.getCurrentTime()
				}

				this.messages.push(userMessage)

				// 清空输入框
				const message = this.inputMessage
				this.inputMessage = ''

				// 滚动到底部
				this.scrollToBottom()

				// 添加AI消息占位符
				const aiMessageId = Date.now() + 1
				const aiMessage = {
					id: aiMessageId,
					type: 'ai',
					content: '',
					imagePending: this.outputType!== 'text',
					imageUrl: '',
					htmlContent: '',
					time: this.getCurrentTime()
				}

				this.messages.push(aiMessage)
				this.scrollToBottom()

				// 清空流式数据缓冲区
				this.streamBuffer = ''
				const idx = this.messages.findIndex(m => m.id === aiMessageId)
				this.$set(this.messages[idx], 'status', 2)
				// 根据类型调用接口
				if (this.type !== 'agent') {
					await this.callChatAPI(message, aiMessageId)
				} else {
					this.isTyping=true
					
					if (idx !== -1&&this.outputType!== 'text') {
						this.$set(this.messages[idx], 'imagePending', true)
						this.$set(this.messages[idx], 'imageUrl', '')
					}
					await this.callImageAPI(message, aiMessageId)
				}

			},

			// 选择图片
			async chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						console.log('选择图片成功:', res)

						// 显示上传loading
						uni.showLoading({
							title: '图片上传中...',
							mask: true
						})

						try {
							// 调用uploadFile方法上传图片
							const result = await uploadFile(res.tempFilePaths[0])

							// 上传成功，保存图片地址
							console.log('图片上传成功:', result)
							this.uploadedImage = result.data.fileUrl // 假设接口返回的图片地址在data.url字段
							this.uploadedImageFile = res.tempFiles

							// 显示上传成功提示
							uni.showToast({
								title: '图片上传成功',
								icon: 'success'
							})
						} catch (error) {
							console.error('图片上传失败:', error)
							// 显示上传失败提示
							uni.showToast({
								title: '图片上传失败',
								icon: 'none'
							})
							// 重置图片状态
							this.uploadedImage = ''
							this.uploadedImageFile = null
						} finally {
							// 隐藏loading
							uni.hideLoading()
						}
					},
					fail: () => {
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						})
					}
				})
			},

			// 移除图片
			removeImage() {
				this.uploadedImage = null
				this.uploadedImageFile = null
			},

			// 复制内容到剪贴板
			copyContent(content) {
				if (!content) {
					uni.showToast({
						title: '没有可复制的内容',
						icon: 'none'
					})
					return
				}

				// 创建临时文本区域用于复制
				const textarea = document.createElement('textarea')
				// 先过滤掉<div class="think">标签及其内容（处理各种可能的空白字符和属性变化）
				let filteredContent = content.replace(/<div\s+class="think"[^>]*>.*?<\/div>/gs, '')
				// 再移除所有剩余的HTML标签
				textarea.value = filteredContent.replace(/<[^>]*>/g, '')
				textarea.style.position = 'fixed'
				textarea.style.left = '-999999px'
				textarea.style.top = '-999999px'
				document.body.appendChild(textarea)
				textarea.focus()
				textarea.select()

				try {
					const successful = document.execCommand('copy')
					if (successful) {
						uni.showToast({
							title: '复制成功',
							icon: 'success'
						})
					} else {
						throw new Error('复制失败')
					}
				} catch (err) {
					console.error('复制失败:', err)
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				} finally {
					document.body.removeChild(textarea)
				}
			},


			// 下载图片
			downloadImage(item) {
				if(this.outputType=='video'){
					uni.showModal({
						content: '请长按视频选择"保存"到手机相册',
						showCancel: false
					});
					return
				}
				try {
					// 安全地提取图片URL，处理可能的null结果
					const matchResult = item.htmlContent?.match(/<img.*?src="(.*?)".*?>/);
					if (!matchResult || !matchResult[1]) {
						uni.showToast({
								title: '没有可下载的图片',
								icon: 'none'
							})
						return
					}

					let imageUrl = matchResult[1];

					// 处理阿里云OSS图片URL，使用代理路径避免跨域问题
					if (imageUrl.includes('aliyuncs.com')) {
						// 替换为代理路径
						imageUrl = '/aliyun-oss' + imageUrl.split('aliyuncs.com')[1];
					}

					// 检查是否在微信环境中
					const isWechat = /MicroMessenger/i.test(navigator.userAgent);

					// 微信环境下的处理逻辑
					if (isWechat) {
						// 微信H5环境下，最佳方案是提示用户长按保存图片
						// 因为微信浏览器限制了很多下载和API调用功能
						uni.showModal({
							title: '微信环境提示',
							content: '微信浏览器限制了直接下载功能，请长按图片选择"保存图片"到手机相册',
							showCancel: false
						});
					} else {
						// 非微信环境使用a标签直接下载
						const downloadWithAnchor = () => {
							try {
								// 创建临时链接
								const link = document.createElement('a');
								link.href = imageUrl;
								link.download = 'image_' + new Date().getTime() + '.png';
								link.style.display = 'none';

								// 将链接添加到DOM并触发点击
								document.body.appendChild(link);
								link.click();

								// 移除链接
								setTimeout(() => {
									document.body.removeChild(link);
								}, 100);

								uni.showToast({
										title: '图片已开始下载',
										icon: 'success'
									})
							} catch (err) {
								console.error('a标签下载失败:', err);
								uni.showModal({
										title: '下载提示',
										content: '当前环境下无法直接下载图片，建议长按图片保存或使用截图功能。',
										showCancel: false
									})
							}
						};

						// 尝试直接下载
						downloadWithAnchor();
					}
				} catch (error) {
					console.error('下载图片过程出错:', error);
					uni.showToast({
							title: '下载图片失败',
							icon: 'none'
						})
				}
			},

			// 选择图片比例
			selectRatio(ratio) {
				this.selectedRatio = ratio
			},
			// 预览图片
			previewImage(imageUrl) {
				this.previewImageUrl = imageUrl;
				this.showImagePreview = true;
			},
			// 关闭图片预览
			closeImagePreview() {
				this.showImagePreview = false;
			},
			// 处理HTML内容中的图片点击
			handleHtmlImageTap(e) {
				// 如果点击的是图片元素
				if (e.target.tagName === 'IMG') {
					const imageUrl = e.target.src;
					this.previewImage(imageUrl);
				}
			},

			// 非 agent（绘图）应用：调用 /api/dify/app/chat-messages
			async callImageAPI(query, messageId) {
				if (!this.appId) {
					uni.showToast({
						title: '应用ID无效',
						icon: 'none'
					})
					return
				}

				try {
					this.isTyping = true

					const payload = {
						appId: parseInt(this.appId),
						body: {
							inputs: {
								image_url: this.uploadedImage,
								size: this.selectedRatio
							},
							query: query,
							conversation_id: this.conversationId,
							//category_id: this.categoryId
						}
					}
					console.log('payload:', payload)

					// 展示等待占位（正方形），loading 已在模板中通过 imagePending 控制
					// 这里发起请求，期望为流式，监听 message_end 结束
					const response = await fetch(API_CONFIG.BASE_URL + '/api/dify/app/chat-messages', {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'Authorization': `Bearer ${uni.getStorageSync('token')}`,
							'Accept': 'text/event-stream'
						},
						body: JSON.stringify(payload)
					})

					if (!response.ok) {
						throw new Error('请求失败: ' + response.status)
					}

					const contentType = response.headers.get('content-type')
					if (contentType && contentType.includes('text/event-stream')) {
						// 以流式方式解析，直到 message_end
						const reader = response.body.getReader()
						const decoder = new TextDecoder()
						let buffer = ''
						let lastAnswerChunk = ''

						let reading = true
						while (reading) {
							const {
								done,
								value
							} = await reader.read()
							if (done) {
								reading = false;
								break
							}
							const chunk = decoder.decode(value, {
								stream: true
							})
							buffer += chunk
							const lines = buffer.split('\n')
							buffer = lines.pop() || ''
							for (const line of lines) {
								if (!line.trim()) continue
								if (!line.startsWith('data: ')) continue
								const jsonStr = line.substring(6)
								if (jsonStr.trim() === '[DONE]') continue
								try {
									const data = JSON.parse(jsonStr)
									if (data.event === 'agent_message' && data.answer) {
										lastAnswerChunk += data.answer
										const messageIndex = this.messages.findIndex(m => m.id === messageId)
										if(this.outputType == 'text'){
											this.messages[messageIndex].htmlContent = this.filterThinkTags(lastAnswerChunk)
										}
										this.scrollToBottom()
									}
									if (data.event === 'message_end') {
										// 得到最终 answer（可能为图片URL或markdown）
										const finalAnswer = this.filterThinkTags(lastAnswerChunk) || ''
										// 如果不是视频类型，才调用finishImageMessage
										if (this.outputType !== 'video') {
											this.finishImageMessage(messageId, finalAnswer)
										} else if (data.message_id) {
											this.startVideoGenerationPolling(messageId, data.message_id)
										}
										this.isTyping = false
										
										return
									}
								} catch (_) {
									/* ignore parse error */
								}
							}
						}
					} else {
						// 非流式：直接处理
						const text = await response.text()
						let data
						try {
							data = JSON.parse(text)
						} catch (e) {
							data = {
								answer: text
							}
						}
						const finalAnswer = (data?.data && (data.data.answer || data.data)) || data?.answer || text ||
							''
						this.finishImageMessage(messageId, finalAnswer)
					}
				} catch (error) {
					this.updateMessageContent(messageId, error.message || '请求失败，请重试')
				} finally {
					this.isTyping = false
				}
			},

			// 结束绘图等待，占位替换为图片或HTML内容
			finishImageMessage(messageId, answer) {
				const messageIndex = this.messages.findIndex(m => m.id === messageId)
				if (messageIndex === -1) return

				// 提取图片URL：支持 markdown ![]() 或直接URL
				// 使用正则表达式提取所有img标签
				const imgRegex = /<img[^>]*>/g;
				const imgMatches = answer.match(imgRegex);
				const filteredContent = imgMatches ? imgMatches.join('') : '';
				console.log('filteredContent',filteredContent)
				
				let imageUrl = filteredContent
				
				if (imageUrl) {
					this.messages[messageIndex].htmlContent = imageUrl
					this.messages[messageIndex].content = ''
				} else {
					// 若不是图片，则作为文本
					this.messages[messageIndex].htmlContent = answer
				}
				this.$set(this.messages[messageIndex], 'status', 1)
				this.messages[messageIndex].imagePending = false
				this.isTyping=false
				this.scrollToBottom()
			},

			// 调用聊天接口
			async callChatAPI(query, messageId) {
				if (!this.appId) {
					uni.showToast({
						title: '应用ID无效',
						icon: 'none'
					})
					return
				}

				try {
					this.isTyping = true
					console.log(this.params)

					// 构建请求参数
					const requestData = {
						appId: parseInt(this.appId), // 确保appId是数字类型
						body: {
							inputs: {
								query: query,
								...this.params
							},
							conversation_id: this.conversationId,
						}
					}

					// 使用流式请求
					await this.streamChatAPI(requestData, messageId)

				} catch (error) {
					console.error('聊天接口调用失败:', error)
					//this.updateMessageContent(messageId, error.message || '网络错误，请重试')
					this.isTyping = false
				}
			},

			// 流式聊天接口
			async streamChatAPI(requestData, messageId) {
				try {
					const response = await fetch(API_CONFIG.BASE_URL + '/api/dify/app/completion-messages', {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'Authorization': `Bearer ${uni.getStorageSync('token')}`,
							'Accept': 'text/event-stream'
						},
						body: JSON.stringify(requestData)
					})

					if (!response.ok) {
						throw new Error(`HTTP error! status: ${response.status}`)
					}
					
					const responseData = await response.json()
					console.log('responseData====',responseData)
					if(responseData.code==61){
						uni.removeStorageSync('token')
						uni.switchTab({
							url:'/'
						})
						return
					}
					if(responseData.code==-1){
						this.updateMessageContent(messageId, responseData.message,true)
						this.isTyping = false
						return
					}

					// 检查是否是流式响应
					const contentType = response.headers.get('content-type')

					if (contentType && contentType.includes('text/event-stream')) {
						// 处理真正的流式响应
						await this.handleStreamResponse(response, messageId)
					} else {
						// 处理普通响应
						const data = await response.text()
						
						this.processCompleteStreamData(data, messageId)
					}

				} catch (error) {
					this.updateMessageContent(messageId, '请求失败: ' + error.message)
					this.isTyping = false
					throw error
				}
			},

			// 处理流式响应
			async handleStreamResponse(response, messageId) {
				try {
					const reader = response.body.getReader()
					const decoder = new TextDecoder()
					let buffer = ''

					let isReading = true
					while (isReading) {
						const {
							done,
							value
						} = await reader.read()

						if (done) {
							this.isTyping = false
							isReading = false
							break
						}

						// 解码数据块
						const chunk = decoder.decode(value, {
							stream: true
						})

						// 添加到缓冲区
						buffer += chunk

						// 处理完整的行
						const lines = buffer.split('\n')
						buffer = lines.pop() || '' // 保留最后一行（可能不完整）

						for (const line of lines) {
							if (line.trim() === '') continue

							if (line.startsWith('data: ')) {
								const jsonStr = line.substring(6)

								if (jsonStr.trim() === '[DONE]') {
									this.isTyping = false
									continue
								}

								try {
									const data = JSON.parse(jsonStr)

									if (data.event === 'message' && data.answer) {
										// 处理Unicode转义字符
										let decodedContent = data.answer
										try {
											decodedContent = data.answer.replace(/\\u[\dA-Fa-f]{4}/g, (match) => {
												return String.fromCharCode(parseInt(match.replace(/\\u/g, ''),
													16))
											})
										} catch (decodeError) {
											// 解码失败，使用原始内容
										}

										// 过滤掉 <think> 标签及其内容
										decodedContent = this.filterThinkTags(decodedContent)

										// 立即显示内容
										this.appendToMessage(messageId, decodedContent)
									}

									if (data.event === 'error') {
										this.updateMessageContent(messageId, data.message || '服务器错误')
										this.isTyping = false
									}

									if (data.event === 'message_end'&&this.outputType=='text') {
											this.isTyping = false
										}

								} catch (parseError) {
									// 解析失败，跳过这行
								}
							}
						}
					}

				} catch (error) {
					this.updateMessageContent(messageId, '流式数据处理失败')
					this.isTyping = false
				}
			},

			// 过滤 <think> 标签及其内容
			filterThinkTags(content) {
				// 移除 <think> 标签及其内容
				let str = content.replaceAll('<think>', '<div class="think">').replaceAll('</think>', '</div>')
				if(this.outputType=='text'){
					str=str.replaceAll('\n','<br>')
				}
				return str
			},

			// 处理完整的流式数据并实现打字效果
			processCompleteStreamData(streamData, messageId) {
				try {
					// 将数据转换为字符串
					const dataStr = typeof streamData === 'string' ? streamData :
						streamData instanceof ArrayBuffer ?
						new TextDecoder().decode(streamData) :
						JSON.stringify(streamData)

					// 按行分割数据
					const lines = dataStr.split('\n')

					// 收集所有的answer内容
					const allAnswers = []

					for (const line of lines) {
						if (line.trim() === '') continue

						// 处理 data: 开头的行
						if (line.startsWith('data: ')) {
							const jsonStr = line.substring(6) // 移除 'data: ' 前缀

							// 跳过 [DONE] 标记
							if (jsonStr.trim() === '[DONE]') {
								continue
							}

							try {
								const data = JSON.parse(jsonStr)

								// 检查是否是消息事件
								if (data.event === 'message' && data.answer) {
									// 处理Unicode转义字符
									let decodedContent = data.answer
									try {
										decodedContent = data.answer.replace(/\\u[\dA-Fa-f]{4}/g, (match) => {
											return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16))
										})
									} catch (decodeError) {
										// 解码失败，使用原始内容
									}

									// 过滤掉 <think> 标签及其内容
									decodedContent = this.filterThinkTags(decodedContent)

									allAnswers.push(decodedContent)
								}

							} catch (parseError) {
								// 解析失败，跳过这行
							}
						}
					}

					// 合并所有内容
					const fullContent = allAnswers.join('')

					// 实现打字效果
					this.startTypingEffect(fullContent, messageId)

				} catch (error) {
					this.updateMessageContent(messageId, '数据解析失败')
					this.isTyping = false
				}
			},

			// 开始打字效果
			startTypingEffect(content, messageId) {
				const messageIndex = this.messages.findIndex(msg => msg.id === messageId)
				if (messageIndex === -1) {
					return
				}

				// 清空消息内容
				this.messages[messageIndex].content = ''

				let currentIndex = 0
				const typingSpeed = 30 // 打字速度（毫秒）

				const typeNextChar = () => {
					if (currentIndex < content.length) {
						// 添加下一个字符
						this.messages[messageIndex].content += content[currentIndex]
						currentIndex++

						// 滚动到底部
						this.scrollToBottom()

						// 继续下一个字符
						setTimeout(typeNextChar, typingSpeed)
					} else {
						// 打字完成
						this.isTyping = false
					}
				}

				// 开始打字
				typeNextChar()
			},

			// 解析流式数据
			parseStreamData(chunkData, messageId) {
				try {
					// 将数据块转换为字符串
					const dataStr = typeof chunkData === 'string' ? chunkData :
						chunkData instanceof ArrayBuffer ?
						new TextDecoder().decode(chunkData) :
						JSON.stringify(chunkData)

					console.log('原始数据字符串:', dataStr)
					console.log('数据类型:', typeof chunkData)
					console.log('消息ID:', messageId)

					// 将新数据添加到缓冲区
					this.streamBuffer += dataStr

					// 按行分割数据
					const lines = this.streamBuffer.split('\n')

					// 保留最后一行（可能不完整）
					this.streamBuffer = lines.pop() || ''

					console.log('分割后的行数:', lines.length)

					for (const line of lines) {
						if (line.trim() === '') continue

						console.log('处理行:', line)

						// 处理 data: 开头的行
						if (line.startsWith('data: ')) {
							const jsonStr = line.substring(6) // 移除 'data: ' 前缀

							console.log('提取的JSON字符串:', jsonStr)

							// 跳过 [DONE] 标记
							if (jsonStr.trim() === '[DONE]') {
								console.log('流式数据结束')
								this.isTyping = false
								continue
							}

							try {
								const data = JSON.parse(jsonStr)
								console.log('解析的JSON数据:', data)

								// 检查是否是消息事件
								if (data.event === 'message' && data.answer) {
									console.log('找到消息内容:', data.answer)

									// 处理Unicode转义字符
									let decodedContent = data.answer
									try {
										// 尝试解码Unicode转义字符
										decodedContent = data.answer.replace(/\\u[\dA-Fa-f]{4}/g, (match) => {
											return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16))
										})
									} catch (decodeError) {
										console.warn('Unicode解码失败，使用原始内容:', decodeError)
									}

									console.log('解码后的内容:', decodedContent)

									// 立即显示内容，实现实时打字效果
									this.appendToMessage(messageId, decodedContent)
								}

								// 检查是否是错误事件
								if (data.event === 'error') {
									console.error('服务器返回错误:', data)
									this.updateMessageContent(messageId, data.message || '服务器错误')
									this.isTyping = false
								}

								// 检查是否是结束事件
								if (data.event === 'message_end') {
									console.log('消息结束')
									this.isTyping = false
								}

							} catch (parseError) {
								console.error('解析JSON失败:', parseError, '原始数据:', jsonStr)
								// 如果JSON解析失败，可能是数据不完整，继续处理下一行
							}
						}
					}
				} catch (error) {
					console.error('处理流式数据失败:', error)
					this.updateMessageContent(messageId, '数据解析失败')
					this.isTyping = false
				}
			},

			// 追加内容到消息（实现打字效果）
			appendToMessage(messageId, newContent) {
				const messageIndex = this.messages.findIndex(msg => msg.id === messageId)

				if (messageIndex === -1) {
					return
				}

				// 直接追加新内容
				this.messages[messageIndex].htmlContent += newContent

				// 立即滚动到底部
				this.scrollToBottom()
			},

			// 显示打字效果
			displayTypingEffect(content, messageId) {
				const messageIndex = this.messages.findIndex(msg => msg.id === messageId)
				if (messageIndex === -1) return

				let currentIndex = 0
				const typingSpeed = 50 // 打字速度（毫秒）

				const typeNextChar = () => {
					if (currentIndex < content.length) {
						this.messages[messageIndex].content += content[currentIndex]
						currentIndex++
						this.scrollToBottom()
						setTimeout(typeNextChar, typingSpeed)
					}
				}

				typeNextChar()
			},

			// 更新消息内容
			updateMessageContent(messageId, content,err) {
				const messageIndex = this.messages.findIndex(msg => msg.id === messageId)
				if (messageIndex !== -1) {
					this.messages[messageIndex].content = content
					if(err){
						this.messages[messageIndex].status = 9
					}
					// 立即滚动到底部
					this.scrollToBottom()
				}
			},

			// 获取当前时间
			getCurrentTime() {
				const now = new Date()
				const hours = now.getHours().toString().padStart(2, '0')
				const minutes = now.getMinutes().toString().padStart(2, '0')
				return `${hours}:${minutes}`
			},

			// 滚动到底部
			scrollToBottom() {
				this.$nextTick(() => {
					this.forceScrollToBottom()
				})
			},

			// 强制滚动到底部
			forceScrollToBottom() {
				try {
					// 获取聊天内容容器
					const chatContent = this.$refs.chatContent
					chatContent.$el.scrollTo(0, 99999999)
				} catch (error) {
					// 备用方案：使用 uni-app 的页面滚动
					try {
						uni.pageScrollTo({
							scrollTop: 999999,
							duration: 0
						})
					} catch (uniError) {
						// 最后的备用方案
						console.warn('滚动到底部失败:', error, uniError)
					}
				}
			},
			
			async getVideoDetail(messageId, conversationMessageId,index){
				console.log(conversationMessageId)
				try {
					// 调用视频生成状态查询接口
					const res = await get('/api/dify/conversation/detail', {
						messageId: conversationMessageId
					})
					const data=res.data
					console.log('视频生成状态查询响应:', data)
					// 查找对应的消息
					const messageIndex = index?index:this.messages.findIndex(msg => msg.id === messageId)
					if (messageIndex === -1) {
						return
					}
					console.log('messageIndex:', messageIndex)
					// 更新任务状态
					if (data.data?.video?.url) {
						// 生成成功，更新视频地址
						this.messages[messageIndex]={
							...this.messages[messageIndex],
							videoUrl:data.data.video?.url,
							status:1,
							imagePending:false
						}
						this.isTyping = false
					} else if (data.status == 4) {
						console.log('data.status===',data.status)
						this.isTyping = false
						this.messages[messageIndex]={
							...this.messages[messageIndex],
							htmlContent:data.response || '视频生成失败',
							status:4,
							imagePending:false
						}
						this.scrollToBottom()
					} else{
						if(messageId){
							setTimeout(()=>{
								this.getVideoDetail(messageId, conversationMessageId)
							},5000)
						}
					}
				
				} catch (error) {
					console.error('查询视频生成状态失败:', error)
					// 出错时可以选择继续轮询，或者在一定次数后停止
				}
			},

			// 开始视频生成状态轮询
			startVideoGenerationPolling(messageId, conversationMessageId) {
				this.getVideoDetail(messageId, conversationMessageId)
			}
		}
	}
</script>

<style scoped>
	.chat-detail-container {
		min-height: 100vh;
		background-color: #3A3052;
		display: flex;
		flex-direction: column;
		position: relative;
	}

	/* 会话列表按钮（输入框左侧） */
	.conversation-list-btn {
		width: 40px;
		height: 40px;
		background-color: #5A506E;
		border-radius: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.conversation-list-btn:active {
		background-color: #5A506E;
		transform: scale(0.95);
	}

	.list-icon {
		color: #F0D9B5;
		font-size: 20px;
		font-weight: bold;
	}

	/* 会话列表弹窗 */
	.conversation-popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1001;
		transition: opacity 0.3s ease;
	}

	.conversation-popup .popup-content {
		position: absolute;
		top: 0;
		left: 0;
		width: 80%;
		height: 100%;
		background-color: #4A4062;
		border-radius: 0;
		overflow-y: auto;
		transform: translateX(-100%);
		animation: slideIn 0.3s ease forwards;
	}

	.popup-content.slide-out {
		animation: slideOut 0.3s ease forwards;
	}

	@keyframes slideIn {
		to {
			transform: translateX(0);
		}
	}

	@keyframes slideOut {
		from {
			transform: translateX(0);
		}

		to {
			transform: translateX(-100%);
		}
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 0;
		background-color: #5A506E;
		border-bottom: none;
		margin-bottom: 0;
	}

	.popup-title {
		color: #F0D9B5;
		font-size: 20px;
		font-weight: 600;
		margin-left: 20px;
	}

	.new-conversation-btn {
		color: #FFFFFF;
		font-size: 14px;
		padding: 5px 15px;
		background-color: #F0D9B5;
		border-radius: 15px;
		margin-right: 20px;
	}

	.new-conversation-text {
		color: #5A506E;
		font-weight: 500;
	}

	.popup-body {
		height: calc(100% - 130px);
		margin-bottom: 20px;
		overflow: auto;
	}

	.loading-indicator {
		text-align: center;
		color: #8F82A8;
		padding: 20px;
	}

	.empty-state {
		text-align: center;
		color: #8F82A8;
		padding: 20px;
	}

	.conversation-group {
		width: calc(100% - 20px);
		transition: background-color 0.2s ease;
		margin: 10px auto;
		padding: 10px;
		border-radius: 10px;
		background-color: #5a506e;
	}

	.conversation-group:active {
		background-color: #444;
	}

	.conversation-time {
		color: #8F82A8;
		font-size: var(--font-size-small);
		display: block;
		margin-bottom: 8px;
	}

	.group-title {
		color: #f0d9b5;
		font-size: 15px;
		line-height: 1.6;
	}

	.popup-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 15px 20px;
		background-color: #5A506E;
		border-top: 1px solid #6A608E;
	}

	.back-chat-btn {
		display: block;
		width: 100%;
		margin: 0 auto;
		padding: 12px;
		color: #fff;
		font-size: 16px;
		font-weight: 600;
		background-color: #8f82a8;
		padding: 10px;
		border-radius: 8px;
		text-align: center;
		cursor: pointer;
		transition: all .3s ease;
		text-align: center;
	}

	/* 作文撰写弹窗样式 */
	.writing-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #52496D;
		z-index: 999;
		overflow-y: auto;
		display: flex;
		flex-direction: column;
	}

	.writing-popup .popup-content {
		padding: 90px 20px 40px;
		width: 100%;
		height: 100%;
		box-sizing: border-box;
	}

	.header-icon {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 40px;
	}

	.icon-img {
		width: 80px;
		height: 80px;
		background-color: #5A506E;
		border-radius: 50%;
		margin-bottom: 15px;
	}

	.title-text {
		color: #FFFFFF;
		font-size: 24px;
		font-weight: 600;
		margin-bottom: 8px;
	}

	.subtitle-text {
		color: #8F82A8;
		font-size: 14px;
	}

	.form-group {
		margin-bottom: 25px;
	}

	.form-label {
		color: #FFFFFF;
		font-size: 16px;
		font-weight: 500;
		margin-bottom: 10px;
		display: block;
	}

	.topic-input {
		width: 100%;
		height: 100px;
		padding: 12px;
		background-color: #5A506E;
		border: 1px solid #8F82A8;
		border-radius: 8px;
		color: #FFFFFF;
		font-size: 16px;
		resize: none;
		box-sizing: border-box;
	}

	.topic-input::placeholder {
		color: #8F82A8;
	}

	.char-count {
		color: #8F82A8;
		font-size: 12px;
		float: right;
		margin-top: 5px;
	}

	.type-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
	}

	.type-btn {
		padding: 8px 16px;
		background-color: #5A506E;
		border: 1px solid #8F82A8;
		border-radius: 20px;
		color: #FFFFFF;
		font-size: 14px;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.type-btn.active {
		background-color: #F0D9B5;
		border-color: #F0D9B5;
		color: #333;
	}

	.word-count-input {
		width: 100%;
		height: 50px;
		padding: 12px;
		background-color: #5A506E;
		border: 1px solid #8F82A8;
		border-radius: 8px;
		color: #FFFFFF;
		font-size: 16px;
		box-sizing: border-box;
	}

	.word-count-input::placeholder {
		color: #8F82A8;
	}

	.generate-btn {
		width: 100%;
		height: 50px;
		background-color: #F0D9B5;
		border: none;
		border-radius: 8px;
		color: #333;
		font-size: 18px;
		font-weight: 600;
		cursor: pointer;
		margin-top: 20px;
	}

	.generate-btn:active {
		background-color: #E0C499;
	}

	.header {
		background-color: #4A4062;
		padding: 10px 65px 10px 15px;
		display: flex;
		align-items: center;
		position: sticky;
		top: 0;
		z-index: 1000;
	}

	.back-btn {
		width: 40px;
		height: 40px;
		background-color: rgba(240, 217, 181, 0.1);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10px;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.back-btn:active {
		background-color: rgba(240, 217, 181, 0.2);
		transform: scale(0.95);
	}

	.back-arrow {
		color: #F0D9B5;
		font-size: 20px;
		font-weight: bold;
	}

	.title {
		flex: 1;
		color: rgba(255, 255, 255, 0.5);
		font-size: 20px;
		font-weight: 600;
		text-align: center;
	}


	.chat-content {
		padding: 20px 20px calc(env(safe-area-inset-bottom) + 20px);
		box-sizing: border-box;
		height: calc(100vh - 44px - 80px);
		overflow-y: auto;
		overflow-x: hidden;
		-webkit-overflow-scrolling: touch;
	}

	.chat-agent {
		height: calc(100vh - 44px - 180px);
	}

	.message-list {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.message-item {
		display: flex;
		flex-direction: column;
		max-width: 80%;
		min-width: 120px;
		font-size: 18px;
	}

	.user-message {
		align-self: flex-end;
	}
	

	.ai-message {
		align-self: flex-start;
	}

	.message-content {
		padding: 12px 16px;
		border-radius: 16px;
		margin-bottom: 4px;
	}

	.user-message .message-content {
		background-color: #F0D9B5;
		color: #333;
	}
	.user-message .message-content  img{
		width: 100px;
	}

	.ai-message .message-content {
		background-color: #4A4062;
		color: #FFFFFF;
	}

	.message-image {
		width: 300px;
		border-radius: 12px;
		display: block;
	}

	/* 图片容器 */
	.image-container {
		position: relative;
		display: inline-block;
	}

	/* 内容容器 */
	.content-container {
		position: relative;
		min-width: 30px;
		min-height: 10px;
	}

	/* 动作按钮基础样式 */
	.action-button {
		position: absolute;
		bottom: -40px;
		right: -10px;
		padding: 4px 8px;
		background-color: rgba(0, 0, 0, 0.7);
		color: white;
		border-radius: 4px;
		font-size: 12px;
		cursor: pointer;
		opacity: 1;
		transition: opacity 0.3s ease;
		z-index: 1;
	}

	.copy-video{
		top:6px;
		bottom:auto;
	}


	/* 当鼠标悬停在容器上时显示按钮 */
	.image-container:hover .action-button,
	.content-container:hover .action-button {
		opacity: 1;
	}

	/* 复制按钮特定样式 */
	.copy-btn {
		
		background-color: rgba(90, 80, 110, 0.7);
	}
	.copy-btn image{
		width: 14px;
		height: 15px;
		opacity: 0.5;
	}

	.copy-btn:active {
		background-color: rgba(90, 80, 110, 0.9);
	}

	/* 下载按钮特定样式 */
	.download-btn {
		background-color: rgba(90, 80, 110, 0.7);
	}

	.download-btn:active {
		background-color: rgba(90, 80, 110, 0.9);
	}

	.image-placeholder {
		width: 240px;
		height: 240px;
		background-color: #5A506E;
		border-radius: 12px;
		position: relative;
		overflow: hidden;
	}

	.spinner {
		position: absolute;
		top: 50%;
		left: 50%;
		width: 36px;
		height: 36px;
		margin: -18px 0 0 -18px;
		border: 3px solid rgba(255, 255, 255, 0.2);
		border-top-color: #F0D9B5;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}
	.spinner-text{
		position: absolute;
		top: calc(50% + 30px);
		width: 100%;
		text-align: center;
		font-size: 12px;
		opacity: 0.5;
	}
	.spinner-text-btn{
		text-decoration: underline;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.message-text {
		font-size: 18px;
		line-height: 1.4;
	}

	.message-time {
		text-align: left;
		padding-left: 10px;
	}

	.time-text {
		color: #8F82A8;
		font-size: 14px;
	}

	.input-area {
		position: sticky;
		bottom: 0;
		z-index: 100;
		background-color: #4A4062;
		padding: 10px 15px;
		border-top: 1px solid #52496D;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.message-input {
		flex: 1;
		height: 40px;
		background-color: #52496D;
		border: 1px solid #8F82A8;
		border-radius: 20px;
		padding: 5px 16px;
		color: #FFFFFF;
		font-size: 18px;
	}

	.message-input::placeholder {
		color: #8F82A8;
	}

	.send-btn {
		background-color: #F0D9B5;
		border-radius: 20px;
		padding: 10px 20px;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.send-btn:active {
		background-color: #E0C090;
		transform: scale(0.95);
	}

	.send-text {
		color: #333;
		font-size: 18px;
		font-weight: 500;
	}

	.send-btn.disabled {
		background-color: #8F82A8;
		cursor: not-allowed;
	}

	.typing-indicator {
		color: #8F82A8;
		font-size: 16px;
		font-style: italic;
	}

	.message-input:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	/* 图片上传区域 */
	.upload-area {
		padding: 10px 0;
		border-bottom: 1px solid #52496D;
		display: flex;
		align-items: flex-end;
		gap: 20px;
	}

	/* 图片比例选择器 */
	.aspect-ratio-selector {
		display: flex;
		align-items: center;
	}

	.ratio-buttons {
		display: flex;
		gap: 8px;
	}

	.ratio-btn {
		width: 60px;
		height: 30px;
		background-color: #5A506E;
		border: 2px solid #8F82A8;
		border-radius: 4px;
		cursor: pointer;
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.ratio-btn.active {
		background-color: #5A506E;
		border-color: #F0D9B5;
	}

	.ratio-btn:active {
		transform: scale(0.95);
	}

	.ratio-text {
		color: #FFFFFF;
		font-size: 16px;
		font-weight: 500;
	}

	.ratio-btn.active .ratio-text {
		color: #F0D9B5;
	}

	.upload-container {
		position: relative;
		width: 80px;
		height: 80px;
		border: 2px dashed #8F82A8;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.upload-container:active {
		border-color: #F0D9B5;
		background-color: rgba(240, 217, 181, 0.1);
	}

	.upload-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.upload-icon {
		font-size: 26px;
		margin-bottom: 4px;
	}

	.upload-text {
		color: #8F82A8;
		font-size: 14px;
	}

	.uploaded-image {
		width: 100%;
		height: 100%;
		border-radius: 6px;
		object-fit: cover;
	}

	.remove-image {
		position: absolute;
		top: -8px;
		right: -8px;
		width: 20px;
		height: 20px;
		background-color: #F44336;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.remove-icon {
		color: #FFFFFF;
		font-size: 16px;
		font-weight: bold;
	}

	/* HTML内容样式 */
	.html-content {
		max-width: 100%;
		overflow-x: auto;
	}
	.html-content .think{
		opacity:0.6;
	}

	.html-content img {
		max-width: 100%;
		height: auto;
		border-radius: 8px;
	}

	/* 图片预览样式 */
	.image-preview {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.9);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}

	.preview-image {
		width: 90%;
		height: 80%;
	}
	
	/* 适配不同设备的提示语位置 */
	@media screen and (max-height: 600px) {
		.save-tip {
			bottom: 30px;
		}
		
		.save-tip-text {
			font-size: 14px;
			padding: 6px 12px;
		}
	}

	.close-preview {
		position: absolute;
		top: 20px;
		right: 20px;
		width: 40px;
		height: 40px;
		background-color: rgba(255, 255, 255, 0.3);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.close-icon {
		color: white;
		font-size: 24px;
		font-weight: bold;
	}

	/* 长按保存提示语样式 */
	.save-tip {
		position: absolute;
		bottom: 120px;
		left: 0;
		right: 0;
		text-align: center;
	}
	
	.save-tip-text {
		color: white;
		font-size: 16px;
		background-color: rgba(0, 0, 0, 0.5);
		padding: 8px 16px;
		border-radius: 20px;
	}

	/* 视频容器样式 */
	.video-container {
		position: relative;
		display: inline-block;
	}

	/* 视频样式 */
	.message-video {
		width: 240px;
		border-radius: 12px;
		display: block;
	}
</style>